package com.haoxuer.discover.area.data.dao.impl;

import com.haoxuer.discover.area.data.dao.AreaDao;
import com.haoxuer.discover.area.data.entity.Area;
import com.haoxuer.discover.data.core.CatalogDaoImpl;
import com.haoxuer.discover.data.core.Finder;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Created by imake on 2017年08月04日10:01:33.
 */
@Repository

public class AreaDaoImpl extends CatalogDaoImpl<Area, Integer> implements AreaDao {
  
  @Override
  public Area findById(Integer id) {
    if (id == null) {
      return null;
    }
    return get(id);
  }
  
  @Override
  public Area save(Area bean) {
    
    add(bean);
    
    
    return bean;
  }
  
  @Override
  public Area deleteById(Integer id) {
    Area entity = super.get(id);
    if (entity != null) {
      getSession().delete(entity);
    }
    return entity;
  }
  
  @Override
  public Area findByName(String name) {
    Finder finder = Finder.create();
    finder.append(" from Area a  where a.name=:name");
    finder.setParam("name", name);
    finder.setMaxResults(2);
    return findOne(finder);
  }
  
  @Override
  public Area findByFullName(String name) {
    Finder finder = Finder.create();
    finder.append(" from Area a  where a.fullName=:name");
    finder.setParam("name", name);
    finder.setMaxResults(2);
    return findOne(finder);
  }
  
  private Area find(String name, String parent) {
    Finder finder = Finder.create();
    finder.append(" from Area a  where a.fullName=:fullName and a.parent.fullName=:parent ");
    finder.setParam("fullName", name);
    finder.setParam("parent", parent);
    return findOne(finder);
  }
  
  @Override
  public Area name(String name, String... parents) {
    Finder finder = Finder.create();
    finder.append(" from Area a  where a.fullName=:fullName or a.name=:simplename");
    finder.setParam("fullName", name);
    finder.setParam("simplename", name);
    finder.setMaxResults(2);
    Long num = countQuery(finder);
    if (num > 1) {
      if (parents != null && parents.length > 0) {
        return find(name, parents[0]);
      }
    }
    return findOne(finder);
  }
  
  @Override
  public Area findByCode(String code) {
    Finder finder = Finder.create();
    finder.append(" from Area a  where a.code=:code");
    finder.setParam("code", code);
    finder.setMaxResults(2);
    return findOne(finder);
  }
  
  @Override
  protected Class<Area> getEntityClass() {
    return Area.class;
  }
  
  @Autowired
  public void setSuperSessionFactory(SessionFactory sessionFactory) {
    super.setSessionFactory(sessionFactory);
  }
}